/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bff.engine.entity.defaultvalue;

import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bff.api.dataprocessor.IDefaultValueConvertor;
import com.inspur.edp.bff.engine.core.exception.BffEngineCoreException;
import com.inspur.edp.bff.engine.core.exception.BffEngineCoreErrorCodes;
import com.inspur.edp.bff.entity.defaultvalue.VoDefaultValue;
import com.inspur.edp.das.commonmodel.IGspCommonElement;
import com.inspur.edp.formserver.viewmodel.GspViewModelElement;
import com.inspur.edp.formserver.viewmodel.GspViewObject;
import lombok.var;

import java.util.HashMap;

public class BffEngineDefaultValueMapConvertor implements IDefaultValueConvertor {

    private GspViewObject voObject;
    private GspBizEntityObject beObject;

    public BffEngineDefaultValueMapConvertor(GspViewObject voObject, GspBizEntityObject beObject) {
        this.voObject = voObject;
        this.beObject = beObject;

    }

    @Override
    public HashMap<String, Object> convertFromVo(VoDefaultValue voDefaultValue) {
        HashMap<String, Object> beDefaultValue = new HashMap<>();
        if (beObject == null || voDefaultValue.getDefaultValue() == null || voDefaultValue.getDefaultValue().size() < 1)
            return beDefaultValue;

        for (var item : voDefaultValue.getDefaultValue().entrySet()) {
            String labelId = item.getKey();
            GspViewModelElement voElement = (GspViewModelElement) voObject.getElementByLabelId(labelId);
            if (!voElement.getMapping().getTargetObjectId().equals(beObject.getID()))
                continue;
            String targetElementId = voElement.getMapping().getTargetElementId();
            IGspCommonElement beElement = beObject.findElement(targetElementId);
            if (beElement == null) {
                String voName=voObject.getBelongModel()==null ? "":voObject.getBelongModel().getName();
                String beName=beObject.getBelongModel()==null ? "":beObject.getBelongModel().getName();

                throw new BffEngineCoreException(BffEngineCoreErrorCodes.GSP_BFF_ENGINE_1033,voName,voObject.getName(),voElement.getName(),
                        targetElementId,beName,beObject.getName());
            }
            beDefaultValue.put(beElement.getLabelID(), item.getValue());
        }

        return beDefaultValue;
    }
}
